package com.banyou.banyou.main.list;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSON;
import com.banyou.banyou.R;
import com.banyou.banyou.adapter.ListAdapter;
import com.banyou.banyou.adapter.SearchAdapter;
import com.banyou.banyou.adapter.TourListAdapter;
import com.banyou.banyou.base.BaseFragment;
import com.banyou.banyou.bean.journey.JourneyBean;
import com.banyou.banyou.bean.journey.query.ParamInfo;
import com.banyou.banyou.bean.journey.query.QueryParamBean;
import com.banyou.banyou.bean.journey.query.TourBean;
import com.banyou.banyou.order.journey.JourneyInfoActivity;
import com.banyou.banyou.order.tourjourney.TourJourneyActivity;
import com.banyou.banyou.util.FontDisplayUtil;
import com.banyou.banyou.util.RxBus;
import com.banyou.banyou.util.ShowToast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.qqtheme.framework.picker.DatePicker;
import cn.qqtheme.framework.picker.DateTimePicker;
import cn.qqtheme.framework.picker.OptionPicker;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

import static com.banyou.banyou.util.Constants.REFRESH_LIST_FRAGMENT;

/**
 * ----------Dragon be here!----------/
 * 　　　┏┓　　　┏┓
 * 　　┏┛┻━━━┛┻┓
 * 　　┃　　　　　　　┃
 * 　　┃　　　━　　　┃
 * 　　┃　┳┛　┗┳　┃
 * 　　┃　　　　　　　┃
 * 　　┃　　　┻　　　┃
 * 　　┃　　　　　　　┃
 * 　　┗━┓　　　┏━┛
 * 　　　　┃　　　┃神兽保佑
 * 　　　　┃　　　┃代码无BUG！
 * 　　　　┃　　　┗━━━┓
 * 　　　　┃　　　　　　　┣┓
 * 　　　　┃　　　　　　　┏┛
 * 　　　　┗┓┓┏━┳┓┏┛
 * 　　　　　┃┫┫　┃┫┫
 * 　　　　　┗┻┛　┗┻┛
 * ━━━━━━神兽出没━━━━━━
 * 类描述：行程单类
 * 创建人：Random
 * 修改时间：
 * 修改备注：
 */

public class ListFragment extends BaseFragment<ListPresenter> implements ListContract.View {

    @BindView(R.id.recycler)
    RecyclerView mRecyclerView;
    @BindView(R.id.swpie_refresh)
    public SwipeRefreshLayout mSwpieRefresh;
    @BindView(R.id.start_time_btn)
    Button mStartTimeBtn;
    @BindView(R.id.end_time_btn)
    Button mEndTimeBtn;
    @BindView(R.id.search_content)
    LinearLayout mSearchContent;
    @BindView(R.id.order_state_btn)
    Button mOrderStateBtn;

    private List<JourneyBean> mList = new ArrayList<>();
    private List<TourBean> mBean = new ArrayList<>();
    private ListAdapter mAdapter;//伴游端适配器
    private TourListAdapter mTourAdaper;//游客端适配器
    private Map<String, String> mMap = new HashMap<>();
    private Map<String, String> mParamMap = new HashMap<>();
    private Map<String, String> mTourMap = new HashMap<>();
    private int mStart = 0, mLimit = 10, mTotal;
    private ParamInfo mParamInfo = new ParamInfo();
    private Subscription mSubscribe;

    @Override
    protected void init() {
        mPresenter.initPresenter(this, new ListModel());
        LinearLayoutManager manager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(manager);
        mAdapter = new ListAdapter(getActivity(), mList);
        mTourAdaper = new TourListAdapter(getActivity(), mBean);
        String userType = getSharedPreference().getString("userType", "");
        if (userType.equals("2")) {
            mRecyclerView.setAdapter(mAdapter);
        } else {
            mRecyclerView.setAdapter(mTourAdaper);
        }
        initListener();
        initMap();

        if (getSharedPreference().getString("userType", "").equals("2")) {
            mPresenter.queryOrder(mMap);//伴游界面下，请求文星接口
        } else {
            mPresenter.queryOrderByTime(mTourMap);//游客界面下，请求吴磊接口
            mOrderStateBtn.setVisibility(View.GONE);
        }

    }

    /**
     * 初始化数据
     */
    private void initMap() {
        mMap.put("start", mStart + "");
        mMap.put("limit", mLimit + "");
        mMap.put("billId", getSharedPreference().getString("billId", ""));
        mTourMap.put("userId", getSharedPreference().getString("userId", ""));
        mTourMap.put("start", mStart + "");
        mTourMap.put("limit", mLimit + "");

        mParamMap.put("start", mStart + "");
        mParamMap.put("limit", mLimit + "");
        mParamInfo.setAttributes(new ParamInfo.AttributesBean());
        mParamInfo.getAttributes().setRelUserId(getSharedPreference().getString("userId", "1"));
    }

    /**
     * 初始化监听器
     */
    private void initListener() {
        //下拉刷新
        mSwpieRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mStart = 0;
                mList.clear();
                mBean.clear();
                if (getSharedPreference().getString("userType", "").equals("2")) {
                    mPresenter.queryOrder(mMap);
                } else {
                    mPresenter.queryOrderByTime(mTourMap);
                }
            }
        });
        //游客端点击事件
        mTourAdaper.setOnItemClickListener(new TourListAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                Intent intent = new Intent(getActivity(), JourneyInfoActivity.class);
                intent.putExtra("orderId", mBean.get(position).getOrderId());
                intent.putExtra("orderState", mBean.get(position).getOrderState());
                startActivity(intent);
            }
        });
        //伴游端点击事件
        mAdapter.setOnItemClickListener(new SearchAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                Intent intent = new Intent(getActivity(), TourJourneyActivity.class);
                intent.putExtra("orderId", mList.get(position).getOrderId());
                intent.putExtra("orderState", mList.get(position).getOrderState() + "");
                startActivity(intent);
            }
        });
        //分页
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                //屏幕中最后一个可见子项的position
                int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
                //当前屏幕所看到的子项个数
                int visibleItemCount = layoutManager.getChildCount();
                //当前RecyclerView的所有子项个数
                int totalItemCount = layoutManager.getItemCount();
                if (visibleItemCount > 0 && lastVisibleItemPosition == totalItemCount - 1 && newState == RecyclerView.SCROLL_STATE_IDLE && mLimit * (mStart + 1) <= mTotal) {
                    if (getSharedPreference().getString("userType", "").equals("2")) {
                        mMap.put("start", "" + mStart++);
                        mPresenter.queryOrder(mMap);
                    } else {
                        mTourMap.put("start", "" + mStart++);
                        mPresenter.queryOrderByTime(mTourMap);
                    }
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
        //注册刷新RxBus
        mSubscribe = RxBus.getInstance().toObserverable().observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<Object>() {
            @Override
            public void call(Object o) {
                if (o instanceof String) {
                    if (o.equals(REFRESH_LIST_FRAGMENT)) {
                        String userType = getSharedPreference().getString("userType", "");
                        mList.clear();
                        mBean.clear();
                        if (userType.equals("2")) {
                            mStart = 0;
                            mMap.put("start", mStart + "");
                            mPresenter.queryOrder(mMap);
                        } else {
                            mStart = 0;
                            mTourMap.put("start", mStart + "");
                            mPresenter.queryOrderByTime(mTourMap);
                        }
                    }
                }
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mSubscribe.unsubscribe();
    }

    @Override
    protected int setLayoutId() {
        return R.layout.fragment_list;
    }

    @Override
    protected ListPresenter initPresenter() {
        return new ListPresenter();
    }

    /**
     * 查询行程单成功
     *
     * @param bean
     */
    @Override
    public void queryOrderSuccess(List<JourneyBean> bean) {
        mTotal = bean.get(0).getTotal();
        bean.remove(0);
        mList.addAll(bean);
        mAdapter.notifyDataSetChanged();
    }

    /**
     * 伴有端按日期查询成功
     *
     * @param bean
     */
    @Override
    public void queryOrderByTimeSuccess(List<TourBean> bean) {
        mTotal = bean.get(0).getTotal();
        bean.remove(0);
        mBean.addAll(bean);
        mTourAdaper.notifyDataSetChanged();
    }

    private String mStartYear, mStartMonth, mStartDay;
    private String mEndYear, mEndMonth, mEndDay;

    @OnClick({R.id.start_time_btn, R.id.end_time_btn, R.id.order_state_btn})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.start_time_btn:
                createDatePicker(new DatePicker.OnYearMonthDayPickListener() {
                    @Override
                    public void onDatePicked(String year, String month, String day) {
                        mStartTimeBtn.setText(year + "-" + month + "-" + day);
                        mStartTimeBtn.setTextColor(getResources().getColor(R.color.orange_ff9933));
                        mStartYear = year;
                        mStartMonth = month;
                        mStartDay = day;
                        if (mEndYear != null && mEndMonth != null && mEndDay != null) {
                            if (!isStartBigThenEnd()) {
                                ShowToast.showToast("开始时间必须小于结束时间");
                                return;
                            } else {
                                requestQueryData(year, month, day);
                            }
                        }

                    }
                });
                break;
            case R.id.end_time_btn:
                createDatePicker(new DatePicker.OnYearMonthDayPickListener() {
                    @Override
                    public void onDatePicked(String year, String month, String day) {
                        mEndTimeBtn.setText(year + "-" + month + "-" + day);
                        mEndTimeBtn.setTextColor(getResources().getColor(R.color.orange_ff9933));

                        mEndYear = year;
                        mEndMonth = month;
                        mEndDay = day;
                        if (mStartYear != null && mStartMonth != null && mStartDay != null) {
                            if (!isStartBigThenEnd()) {
                                ShowToast.showToast("开始时间必须小于结束时间");
                                return;
                            } else {
                                requestQueryData(year, month, day);
                            }
                        }
                    }
                });
                break;
            case R.id.order_state_btn:
                OptionPicker picker = new OptionPicker(getActivity(), new String[]{"已下单", "待接单", "已完成", "待审核", "已取消", "审核不同过"});
                picker.setOnOptionPickListener(new OptionPicker.OnOptionPickListener() {
                    @Override
                    public void onOptionPicked(int index, String item) {
                        mOrderStateBtn.setText(item);
                        mOrderStateBtn.setTextColor(getResources().getColor(R.color.orange_ff9933));
                        switch (index) {
                            case 0:
                                mParamInfo.setOrderState("2");
                                break;
                            case 1:
                                mParamInfo.setOrderState("3");
                                break;
                            case 2:
                                mParamInfo.setOrderState("5");
                                break;
                            case 3:
                                mParamInfo.setOrderState("7");
                                break;
                            case 4:
                                mParamInfo.setOrderState("8");
                                break;
                            case 5:
                                mParamInfo.setOrderState("9");
                                break;
                        }
                        mParamMap.put("requestInfo", JSON.toJSONString(mParamInfo));
                        mPresenter.queryOrderByParam(mParamMap);
                    }
                });
                picker.show();
                break;
        }
    }

    /**
     * 请求数据
     *
     * @param year
     * @param month
     * @param day
     */
    private void requestQueryData(String year, String month, String day) {
        mTourMap.put("userId", getSharedPreference().getString("userId", ""));
        mTourMap.put("st", mStartYear + "-" + mStartMonth + "-" + mStartDay);
        mTourMap.put("et", mEndYear + "-" + mEndMonth + "-" + mEndDay);
        if (getSharedPreference().getString("userType", "1").equals("1")) {
            mPresenter.queryOrderByTime(mTourMap);
            mBean.clear();
        } else {
            mParamInfo.getAttributes().setBeginDate(year + "-" + month + "-" + day);
            mParamInfo.getAttributes().setEndDate(mEndDay + "-" + mEndMonth + "-" + mEndDay);
            mParamMap.put("requestInfo", JSON.toJSONString(mParamInfo));
            mPresenter.queryOrderByParam(mParamMap);
            mList.clear();
        }
    }

    /**
     * 验证起始时间是否小于结束时间
     *
     * @return
     */
    private boolean isStartBigThenEnd() {
        int startYear = Integer.parseInt(mStartYear);
        int endYear = Integer.parseInt(mEndYear);
        int startMonth = Integer.parseInt(mStartMonth);
        int endMonth = Integer.parseInt(mEndMonth);
        int startDay = Integer.parseInt(mStartDay);
        int endDay = Integer.parseInt(mEndDay);
        boolean isEndBigThenStart = startYear > endYear ? false : startYear < endYear ? true : startMonth > endMonth ? false : startMonth < endMonth ? true : startDay > endDay ? false : startDay < endDay ? true : false;
        return isEndBigThenStart;
    }

    /**
     * 创建DatePicker
     */
    private void createDatePicker(DatePicker.OnYearMonthDayPickListener listener) {
        DatePicker picker = new DatePicker(getActivity(), DateTimePicker.YEAR_MONTH_DAY);
        picker.setCanceledOnTouchOutside(true);
        picker.setUseWeight(true);
        picker.setTopPadding(FontDisplayUtil.dip2px(20));
        picker.setRangeStart(2016, 10, 1);
        picker.setRangeEnd(2020, 10, 2);
        picker.setSelectedItem(2017, 5, 14);
        picker.setOnDatePickListener(listener);
        picker.show();
    }

}
